package com.jingdianjichi.subject.application.context;


import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 用户登录信息（id）的上下文对象
 * @return:
 * @Author:  sky
 * @date:  2024/11/23 23:22
 */
public class LoginContextHolder {

//    private static final ThreadLocal<Map<String,Object>> THREAD_LOCAL
//            = new ThreadLocal<>();

    private static final InheritableThreadLocal<Map<String,Object>> THREAD_LOCAL
            = new InheritableThreadLocal<>();

//    private static final TransmitThreadLocal<Map<String,Object>> THREAD_LOCAL
//            = new TransmitThreadLocal<>();

    public static void set(String key, Object val){
        Map<String,Object> map = getThreadLocalMap();
        map.put(key, val);
    }

    public static Object get(String key){
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        return threadLocalMap.get(key);
    }

    public static String getLoginId(){
        return (String) getThreadLocalMap().get("loginId");
    }

    public static void remove(){
        THREAD_LOCAL.remove();
    }

    public static Map<String,Object> getThreadLocalMap(){
        Map<String, Object> map = THREAD_LOCAL.get();
        if(Objects.isNull(map)){
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

}
